package com.wiserun.RestFul.RestfulAction;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wiserun.RestFul.mapper.AmeOrgMapper;
import com.wiserun.RestFul.mapper.PncsOrganizationMapper;
import com.wiserun.RestFul.model.*;
import com.wiserun.RestFul.service.*;
import com.wiserun.common.consts.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.wiserun.common.model.ResponseData;
import io.swagger.annotations.Api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "Restful接口调用实例")
@Controller()
public class RestfulAction {
    private static final Logger logger = LoggerFactory.getLogger(RestfulAction.class);
    @Autowired
    private ClientAction ca;

    //放入配置文件
    @Value("${restful.systemIP}")
    private String systemIP = "";
    //从配置文件yml中获取北森的参数
    @Value("${beisenToken.grant_type}")
    private String grant_type = "";//必填参数grant_type
    @Value("${beisenToken.app_key}")
    private String app_key = "";
    @Value("${beisenToken.app_secret}")
    private String app_secret = "";
    @Value("${restful.tokenpath}")
    private String tokenpath = "";
    @Autowired
    private BeisenApiTokenService beisenApiTokenService;

    /**
     * 获取北森的access——token，通过获取的token访问北森API
     *
     * @param request
     * @return 获取北森的token
     * 接口访问:http://127.0.0.1:8080/restfulToken/
     */
    @RequestMapping(value = "/restfulToken", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject restfulToken(HttpServletRequest request) {
        // logger.info("RestfulAction.testRestFul.restfulAuth");
        String apiURL = systemIP + tokenpath;
        //构成传入参数
        JSONObject parm = new JSONObject();
        parm.put("apiURL", apiURL);
        parm.put("grant_type", grant_type);
        parm.put("app_key", app_key);
        parm.put("app_secret", app_secret);
        //放入post方法执行
        JSONObject jsonObject = ca.BeisenToken(parm);
        //将返回的jsonobject 转化成 实体类对象
        JSONObject beisenToken_json = JSONObject.parseObject(jsonObject.toString());
        BeisenToken beisenToken = JSON.toJavaObject(beisenToken_json, BeisenToken.class);
        logger.info("转换后的实体对象======>" + beisenToken);
        //String access_token=jsonObject.getString("access_token");
        //JSONObject data=jsonObject.getJSONObject("data");
        //String token_type=jsonObject.getString("token_type");
        //todo 将获取到的北森接口数据存入到pncs数据库
        int count = beisenApiTokenService.addToken(beisenToken);
        jsonObject.put("是否存储pncs数据库", "存储成功");
        if (count == 0) {
            jsonObject.put("是否存储pncs数据库", "存储失败");
        }
        //返回北森数据
        return jsonObject;
    }

    /***
     * 根据时间获取北森所有的组织机构，并更新到pncs数据库中
     * @param request 需要的参数信息
     * StartTime 时间范围开始时间
     * stopTime 时间范围结束时间
     * columns 查询列
     * PageIndex 页码 1-100
     * PageSize  每页数量1-300
     * WithDisabled 是否包含离职的记录
     * WithDeleted 是否包含删除的记录
     * @return
     */
    @Value("${restful.organization}")
    private String organization = "";
    @Autowired
    private PncsOrganizationService pncsOrganizationService;

    @RequestMapping(value = "/getAllOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData getAllOrganization(HttpServletRequest request) throws ParseException {
        ResponseData rd = new ResponseData();//返回前台对象
        // 	从数据库获取token
        String token = beisenApiTokenService.getNewToken();
        logger.info("获取到的token======>" + token);

        //从request中获取传入的jsonObject对象
        BufferedReader streamReader = null;
        JSONObject jsonObject = null;
        try {
            if (request.getInputStream() == null) {
                return new ResponseData(Constants.PARAMS_ERROR);
            }
            streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            rd.setCode(50002);
            rd.setMessage("请求参数填写错误");
            return rd;
        }
        if (jsonObject == null) {
            return new ResponseData(Constants.REQUEST_PARAMS_ERROR);
        }
        logger.info("前台传的json请求参数========>" + jsonObject.toString());
        // logger.info("RestfulAction.testRestFul.restfulAuth");
        String apiURL = systemIP + organization;
        jsonObject.put("apiURL", apiURL);
        jsonObject.put("token", token);
        //放入post方法执行
        JSONObject responsedata = ca.BeisenOrganization(jsonObject);
        if (responsedata == null) {//接口发生异常通知前端
            rd.setCode(50001);
            rd.setMessage("调用接口发生错误，请联系技术人员处理");
            return rd;
        }
        // 北森token过期,重新获取token并重新调用
        if (responsedata != null) {
            String message = responsedata.getString("message");
            if (message != null) {
                if (message.equals("un-authorized")) {
                    //token已过期，重新调用接口
                    String token_new = ca.createToken();
                    jsonObject.put("token", token_new);
                    responsedata = ca.BeisenOrganization(jsonObject);
                }
            }
        }

        //获取数据失败
        if (!(responsedata == null)) {
            if ((responsedata.getString("message") != null) || (responsedata.getString("total") == null)) {
                rd.setCode(50001);
                rd.setMessage("调用接口发生错误，请联系技术人员处理");
                return rd;
            }
        }
        JSONArray data = responsedata.getJSONArray("data");
        boolean isLastData = responsedata.getBoolean("isLastData");
        String scrollId = responsedata.getString("scrollId");
        //Integer total = responsedata.getInteger("Total");
        //String message = responsedata.getString("Message");
        List<Organization> organizations = new ArrayList<>();
        logger.error("获取到的data数据========>" + data.toJSONString());
        // 获取到的数据解析存入到organizations列表
        this.setOrgList(JSONArray.parseArray(data.toJSONString(), JSONObject.class), organizations);
        while (!isLastData) {//再次获取接口内容
            //重新组装请求参数，将scrollId 放到请求参数列表中
            jsonObject.put("scrollId", scrollId);
            responsedata = ca.BeisenOrganization(jsonObject);//调用接口
            //获取接口返回的数据
            JSONArray data2 = responsedata.getJSONArray("data");
            isLastData = responsedata.getBoolean("isLastData");
            scrollId = responsedata.getString("scrollId");
            // 获取到的数据解析存入到organizations列表
            this.setOrgList(JSONArray.parseArray(data2.toJSONString(), JSONObject.class), organizations);
        }
        //批量添加组织机构
        HashMap<String, Integer> counts = pncsOrganizationService.batchAddOgranization(organizations);//成功插入条数
        //返回前台，根据需要替换

        rd.setCode(200);
        rd.setMessage("success");
        rd.setData("新增org=" + counts.get("sum_add") + "条,更新org=" + counts.get("sum_update") + "条");
        //返回北森数据
        return rd;
    }

    @Value("${restful.users}")
    private String users = "";
    @Autowired
    private PncsUserService pncsUserService;
    @Autowired
    private PncsUserRecordService pncsUserRecordService;
    @Autowired
    private PncsUserOrgService pncsUserOrgService;

    /***
     * 获取北森用户信息-用户任职记录-存入到数据中心库
     * @param request 请求参数列表
     * @return 返回响应参数
     */
    @RequestMapping(value = "/getUsers", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData getUsersFromBeisenApi(HttpServletRequest request) {
        ResponseData rd = new ResponseData();//返回前台数据
        // 	从数据库获取token
        String token = beisenApiTokenService.getNewToken();
        logger.error("获取到的token======>" + token);
        //从request中获取传入的jsonObject对象
        BufferedReader streamReader = null;
        JSONObject jsonObject = null;
        try {
            streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            rd.setCode(50002);
            rd.setMessage("请求参数填写错误");
            return rd;
        }
        if (jsonObject == null) {
            return new ResponseData(Constants.PARAMS_ERROR);
        }
        logger.info("前端提交的json参数列表========>" + jsonObject.toString());

        // logger.info("RestfulAction.testRestFul.restfulAuth");
        String apiURL = systemIP + users;
        jsonObject.put("apiURL", apiURL);
        jsonObject.put("token", token);
        //放入post方法执行
        JSONObject responsedata = ca.BeisenUsers(jsonObject);
        if (responsedata == null) {//接口发生异常通知前端
            rd.setCode(50001);
            rd.setMessage("调用接口发生错误，请联系技术人员处理");
            return rd;
        }
        // 北森token过期,重新获取token并重新调用
        if (responsedata != null) {
            String message = responsedata.getString("message");
            if (message != null) {
                if (message.equals("un-authorized")) {
                    //token已过期，重新调用接口
                    String token_new = ca.createToken();
                    jsonObject.put("token", token_new);
                    responsedata = ca.BeisenUsers(jsonObject);
                }
            }
        }

        //获取数据失败
        if (!(responsedata == null)) {
            if ((responsedata.getString("message") != null) || (responsedata.getString("total") == null)) {
                rd.setCode(50001);
                rd.setMessage("调用接口发生错误，请联系技术人员处理");
                return rd;
            }
        }

        JSONArray data = responsedata.getJSONArray("data");
        Integer total = responsedata.getInteger("total");
        Boolean isLastData = responsedata.getBoolean("isLastData");
        String scrollId = responsedata.getString("scrollId");
        logger.info("获取到的data数据========>" + data.toString());
        logger.info("获取到的total数据========>" + total.toString());
        logger.info("isLastData========>" + jsonObject.toString());
        logger.info("scrollId========>" + jsonObject.toString());
        List<User> users = new ArrayList<>();//user用户实体集合
        List<UserRecord> userRecords = new ArrayList<>();// userrecord实体集合
        List<UserOrg> userOrgs = new ArrayList<>();//todo USER_ORG实体集合
        List<JSONObject> dataArr = JSONArray.parseArray(data.toJSONString(), JSONObject.class);
        this.setUserList(dataArr, users);//用户数据填充到用户list
        this.setUserRecordList(dataArr, userRecords);//用户record数据填充到用户list
        this.setUserOrgList(dataArr, userOrgs);//user_Org数据

        while (!isLastData) {//通过scrollId继续获取剩余的数据

            jsonObject.put("scrollId", scrollId);//组装请求参数列表，传入scrollId
            responsedata = ca.BeisenUsers(jsonObject);//再次抓取接口数据
            isLastData = responsedata.getBoolean("isLastData");
            JSONArray data2 = responsedata.getJSONArray("data");
            this.setUserList(JSONArray.parseArray(data2.toJSONString(), JSONObject.class), users);//用户数据填充到用户list
            this.setUserRecordList(JSONArray.parseArray(data2.toJSONString(), JSONObject.class), userRecords);//用户数据填充到用户list
            this.setUserOrgList(JSONArray.parseArray(data2.toJSONString(), JSONObject.class), userOrgs);//user_Org数据
        }
        //批量添加用户
        HashMap<String, Integer> counts_user = pncsUserService.addUsers(users);//成功插入条数
        //批量添加用户任职记录
        HashMap<String, Integer> counts_userRecord = pncsUserRecordService.addUserRecord(userRecords);//成功插入条数
        // 批量插入user_org表
        HashMap<String, Integer> stringIntegerHashMap = pncsUserOrgService.addUserOrgs(userOrgs);
        //返回前台，根据需要替换

        rd.setCode(200);
        rd.setMessage("success");
        rd.setData("新增user=" + counts_user.get("sum_add") + "数条" +
                "；修改user=" + counts_user.get("sum_update") + "条" +
                "；新增userRecord=" + counts_userRecord.get("sum_add") + "条" +
                "；修改userRecord=" + counts_userRecord.get("sum_update") + "条" +
                "；新增useroRG=" + stringIntegerHashMap.get("sum_add") + "条" +
                "；修改useroRG=" + stringIntegerHashMap.get("sum_update") + "条");
        //返回北森数据
        return rd;
    }

    /***
     *  将组织机构 json数组的数据 转化成 list实体对象
     * @param jsons json数组对象
     * @param orgs 组装的实体类列表
     */
    public void setOrgList(List<JSONObject> jsons, List<Organization> orgs) {
        for (JSONObject json : jsons) {
            JSONObject responsedata_str = JSONObject.parseObject(json.toString());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
            //将北森接口日期格式转换成date格式
            try {
                responsedata_str.put("CreatedTime", df.parse(responsedata_str.getString("establishDate")));
                responsedata_str.put("StartDate", df.parse(responsedata_str.getString("startDate")));
                responsedata_str.put("stopDate", df.parse(responsedata_str.getString("stopDate")));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取到的北森接口，没有此参数名称");

            }
            System.err.println(responsedata_str);
            Organization organization = JSON.toJavaObject(responsedata_str, Organization.class);
            orgs.add(organization);
        }
    }

    /***
     * 将用户 json数组的数据 转化成 list实体对象
     * @param jsons
     * @param users 组装的实体类列表
     */
    public void setUserList(List<JSONObject> jsons, List<User> users) {
        for (JSONObject json : jsons) {
            JSONObject user = json.getJSONObject("employeeInfo");
            //logger.info("获取到的user数据========>" + user.toJSONString());
            JSONObject responsedata_str = JSONObject.parseObject(user.toString());
            //record记录里面的empstatus 写入到员工表中
            JSONObject userRecord = json.getJSONObject("recordInfo");
            //logger.error("获取到的userRecord数据========>" + userRecord.toJSONString());
            JSONObject responsedata_userRecord = JSONObject.parseObject(userRecord.toString());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            //将北森接口日期格式转换成date格式
            try {
                if (responsedata_str.getString("birthday") != null) {
                    responsedata_str.put("birthday", df.parse(responsedata_str.getString("birthday")));
                }
                if (responsedata_str.getString("workDate") != null) {
                    responsedata_str.put("workDate", df.parse(responsedata_str.getString("workDate")));
                }
                if (responsedata_str.getString("graduateDate") != null) {
                    responsedata_str.put("graduateDate", df.parse(responsedata_str.getString("graduateDate")));

                }
                if (responsedata_str.getString("createdTime") != null) {
                    responsedata_str.put("createdTime", df.parse(responsedata_str.getString("createdTime")));

                }
                if (responsedata_str.getString("modifiedTime") != null) {
                    responsedata_str.put("modifiedTime", df.parse(responsedata_str.getString("modifiedTime")));
                }
                if (responsedata_userRecord.getString("employeeStatus") != null) {
                    //if (responsedata_userRecord.getString("employeeStatus").equals("8")) {//所有状态都同步
                        responsedata_str.put("status", responsedata_userRecord.getString("employeeStatus"));
                    //}
                }
                if (responsedata_userRecord.getString("employType") != null) {
                    //if (responsedata_userRecord.getString("employeeStatus").equals("8")) {//所有状态都同步
                    responsedata_str.put("type", responsedata_userRecord.getString("employType"));
                    //}
                }
            } catch (ParseException e) {
                e.printStackTrace();
                logger.error("获取到的北森接口，没有此参数名称");

            }
            users.add(JSON.toJavaObject(responsedata_str, User.class));
            //logger.info("获取到的user数据========>" + responsedata_str);
        }
    }

    /***
     * 将用户 json数组的数据 转化成 list实体对象
     * @param jsons
     * @param userRecords 组装的实体类列表
     */
    public void setUserRecordList(List<JSONObject> jsons, List<UserRecord> userRecords) {
        for (JSONObject json : jsons) {
            JSONObject userRecord = json.getJSONObject("recordInfo");
            //logger.error("获取到的userRecord数据========>" + userRecord.toJSONString());
            JSONObject responsedata_str = JSONObject.parseObject(userRecord.toString());

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            //将北森接口日期格式转换成date格式
            try {
                if (responsedata_str.getString("startDate") != null) {
                    responsedata_str.put("startDate", df.parse(responsedata_str.getString("startDate")));
                }
                if (responsedata_str.getString("stopDate") != null) {
                    responsedata_str.put("stopDate", df.parse(responsedata_str.getString("stopDate")));
                }
                if (responsedata_str.getString("lastWorkDate") != null) {
                    responsedata_str.put("lastWorkDate", df.parse(responsedata_str.getString("lastWorkDate")));
                }
                if (responsedata_str.getString("regularizationDate") != null) {
                    responsedata_str.put("regularizationDate", df.parse(responsedata_str.getString("regularizationDate")));
                }
                if (responsedata_str.getString("probationActualStopDate") != null) {
                    responsedata_str.put("probationActualStopDate", df.parse(responsedata_str.getString("probationActualStopDate")));
                }
                if (responsedata_str.getString("probationStartDate") != null) {
                    responsedata_str.put("probationStartDate", df.parse(responsedata_str.getString("probationStartDate")));
                }
                if (responsedata_str.getString("createdTime") != null) {
                    responsedata_str.put("createdTime", df.parse(responsedata_str.getString("createdTime")));

                }
                if (responsedata_str.getString("modifiedTime") != null) {
                    responsedata_str.put("modifiedTime", df.parse(responsedata_str.getString("modifiedTime")));
                }
            } catch (ParseException e) {
                e.printStackTrace();
                logger.error("获取到的北森接口，没有此参数名称");

            }
            userRecords.add(JSON.toJavaObject(responsedata_str, UserRecord.class));
            //logger.info("获取到的userRecord数据========>" + responsedata_str);
        }
    }


    public void setUserOrgList(List<JSONObject> jsons, List<UserOrg> userOrgs) {
        for (JSONObject json : jsons) {
            JSONObject userOrg = json.getJSONObject("recordInfo");
            //logger.error("获取到的userOrg数据========>" + userOrg.toJSONString());
            JSONObject responsedata_str = JSONObject.parseObject(userOrg.toString());


            userOrgs.add(JSON.toJavaObject(responsedata_str, UserOrg.class));
            //logger.info("获取到的userOrg数据========>" + responsedata_str);
            //logger.info("获取到的userOrg实体========>" + userOrgs.toString());
        }
    }

    @Autowired
    public PncsOrganizationMapper mapperOrg;

    @Autowired
    public AmeOrgMapper ameOrgMapper;

    /***
     * 1.先调用企业微信获取token接口，根据appid 和通讯录secret获取权限
     * https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww54b17312ed3809aa&corpsecret=7m-InFDMLbLhn9G0XdrkcYduTrq5AMT_R9OZBQASe9A
     * 2.获取数据库的数据，根据oid删除
     * 批量删除企业微信组织机构信息
     * @return 删除成功的数量
     */
    @RequestMapping(value = "/deleteOrg", method = {RequestMethod.POST})
    @ResponseBody
    public int batchDeleteWechatOrg() {
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse execute;
        String result = "";
        JSONObject jsonObject = null;
        int num = 0;

        String token = "pIbtPa-9POOdDsq-KkCZeUhTWCkhTJxOxNV-H9BQoOkHsMEYiQ3PSozMtPC8nv2xgy0WTswJ1io4iphTEcQAonzbUsJqQIwVKZZIdkS3gtU04scLHvQI-ZzQSfs-Bmgj21QVjDFRFKTaGmRGKVgupmpRrAUrLokSvSClvxW1XvhgBH4Q5mqoAGLUfxpwfmQ_BJkRI-ohEWAcGh-mcVv4Fw";

        // logger.info("RestfulAction.testRestFul.restfulAuth");
        List<AmeOrg> organizations = ameOrgMapper.getOrganization();
        for (AmeOrg ameOrg  : organizations) {
            System.err.println("===================" + ameOrg.getOrgid());
            String apiURL = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + token + "&id=" + ameOrg.getOrgid();
            //构成传入参数
            JSONObject parm = new JSONObject();
            //放入post方法执行

            HttpPost request = new HttpPost(apiURL);
            // 浏览器表示
            request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
            // 传输的类型 不正确时会报错
            request.addHeader("Content-Type", "application/x-www-form-urlencoded");
            try {
                // 创建请求参数
                JSONObject json = new JSONObject();
                //执行请求
                execute = httpClient.execute(request);
                HttpEntity entity = execute.getEntity();
                //logger.error("返回的数据========>"+entity);
                result = EntityUtils.toString(entity, "GBK");
                //logger.error("转换成String的数据=======>"+result);
                jsonObject = JSON.parseObject(result);
                String errcode = jsonObject.getString("errcode");
                if (errcode.equals("0")) {
                    num++;
                }
                System.err.println(jsonObject.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return num;
    }
}

